import torch
import numpy as np

"""
    pytorch 初始化方法
"""
def init():
    # 列表初始化
    x = torch.tensor([[1, 2, 3], [4, 5, 6]])
    print(x)
    x = np.array([[1, 2, 3], [4, 5, 6]])
    x = torch.from_numpy(x)
    print(x)

    # 固定值
    x = torch.zeros(1, 3)
    print(x)
    x = torch.ones(1, 3)
    print(x)
    x = torch.full((1, 3), 0.2)
    print(x)
    x = torch.eye(2)
    print(x)

    x = torch.arange(1, 10, 2)
    print(x)
    x = torch.linspace(1, 10, 3)
    print(x)

    # 随机初始化
    x = torch.rand((1, 3))
    print(x)
    x = torch.randn((1, 3))
    print(x)
    x = torch.randint(-100, 100, (1, 3))
    print(x)


def convert():
    x = torch.tensor([1, 2, 3])
    print(x.bool())
    print(x.double())
    print(x.bool())
    print(x.short())

def arithmetic():
    x = torch.tensor([1, 2, 3])
    y = torch.tensor([4, 5, 6])
    print(x + y)
    x.add(y)
    print(x)
    x.add_(y)
    print(x)

    print(x.true_divide(y))
    print(x.matmul(y))
    print(x * y)
    print(x ** 2)
    print(x.dot(y))

    x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    print(x.matrix_power(2))

    y = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

def broadcast():
    x = torch.randint(1, 10, (2, 3))
    y = torch.randint(1, 10, (1, 3))
    print(x, y, x + y, sep='\n')

def operation():
    x = torch.tensor([1, 2, 3])
    y = torch.tensor([4, 5, 6])
    sum_x = x.sum()
    mean_x = x.double().mean()
    abs_x = x.abs()
    max_x, max_idx =  x.max(dim=0)
    min_x, min_idx = x.min(dim=0)

    z = torch.rand((3, 3))
    max_arg = torch.argmax(z, dim = 0)
    min_arg = torch.argmin(z, dim = 0)
    print(z, max_arg, min_arg, sep='\n')

def index():
    # 切片操作
    x = torch.rand((3, 4, 5))
    print(x[0, :].shape)
    print(x[0, :, 0].shape)
    print(x[[1, 2], :].shape)

    # 条件选择
    y = torch.arange(10)
    print(y[y % 2 == 0])

    # 条件操作, y 中大于 5 的取 y, 不符和的取平方
    print(torch.where(y > 5, y, y ** 2))
    print(torch.unique(torch.tensor([0, 0, 1, 1])))

def shape():
    x = torch.arange(9)
    y = torch.arange(9)
    x_3x3 = x.view(3, 3)
    y_3x3 = y.reshape(3, 3)
    x_3x3.transpose_(0, 1)
    y_3x3.transpose_(0, 1)
    y.reshape(-1)



if __name__ == '__main__':
    # device = 'cuda' if torch.cuda.is_available() else 'cpu'
    # init()
    # convert()
    # arithmetic()
    # broadcast()
    # operation()
    # index()
    shape()